#!/bin/bash
set -e

# ==============================
# 用户可修改配置
# ==============================
ZIP_FILE="mosquitto-master.zip"                  # 源码 zip 文件
WORK_DIR="$PWD"                                  # 当前目录
OUTPUT_DIR="$WORK_DIR/arm64-libs"               # 最终交叉库输出目录
TOOLCHAIN_FILE="$WORK_DIR/toolchain-arm64.cmake" # 工具链文件路径

# 交叉编译器路径（需自己确认）
C_COMPILER="/usr/bin/aarch64-linux-gnu-gcc"
CXX_COMPILER="/usr/bin/aarch64-linux-gnu-g++"

# ==============================
# 准备工具链文件
# ==============================
cat > "$TOOLCHAIN_FILE" <<EOL
set(CMAKE_SYSTEM_NAME Linux)
set(CMAKE_SYSTEM_PROCESSOR aarch64)

set(CMAKE_C_COMPILER   $C_COMPILER)
set(CMAKE_CXX_COMPILER $CXX_COMPILER)

set(CMAKE_FIND_ROOT_PATH $OUTPUT_DIR)

set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
EOL

# ==============================
# 解压源码
# ==============================
if [ ! -d "mosquitto-master" ]; then
    echo "解压 $ZIP_FILE ..."
    unzip "$ZIP_FILE"
fi

# ==============================
# 创建交叉编译目录
# ==============================
cd mosquitto-master
mkdir -p build-arm64
cd build-arm64

# ==============================
# 配置 CMake
# ==============================
echo "配置 CMake ..."
cmake .. \
  -DCMAKE_TOOLCHAIN_FILE="$TOOLCHAIN_FILE" \
  -DWITH_STATIC_LIBRARIES=ON \
  -DWITH_TLS=OFF \
  -DBUILD_SHARED_LIBS=OFF \
  -DWITH_MAN_PAGES=OFF

# ==============================
# 编译
# ==============================
echo "开始编译 ..."
make -j$(nproc)

# ==============================
# 拷贝库和头文件
# ==============================
mkdir -p "$OUTPUT_DIR/lib" "$OUTPUT_DIR/include"

echo "拷贝静态库和头文件 ..."
cp lib/*.a "$OUTPUT_DIR/lib/"
cp ../lib/*.h "$OUTPUT_DIR/include/"

echo "交叉编译完成，库文件位于 $OUTPUT_DIR/lib，头文件位于 $OUTPUT_DIR/include"
